package com.thinkgem.jeesite.modules.self.web;

import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.reader.entity.Reader;
import com.thinkgem.jeesite.modules.reader.entity.ReaderRoler;
import com.thinkgem.jeesite.modules.reader.service.ReaderRolerService;
import com.thinkgem.jeesite.modules.reader.service.ReadersService;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author John
 * @Date 2016/10/15
 */
@Controller
public class LoginController extends BaseController{

    @Autowired
    private ReadersService readerService;

    @Autowired
    private ReaderRolerService readerRolerService;

    /**
     * 自助服务首页
     */
    @RequestMapping("tologin")
    public String tologin(String toPage, String loginType, Model model){
        model.addAttribute("toPage", toPage);
        if(StringUtils.isNotEmpty(loginType)){
            return "modules/login";
        }
        else{
            List<Dict> loginTypes = DictUtils.getDictList("loginType");
            if(loginTypes.size() >= 2){
                model.addAttribute("loginTypes", loginTypes);
                return "modules/chooselogin";
            }
            else{
                return "modules/login";
            }
        }
    }

    @RequestMapping("login")
    public String login(String rdCardno, String toPage, Model model, HttpSession session){
        if(StringUtils.isNotEmpty(rdCardno)){
            Reader reader = readerService.getReaderInfoBySn(rdCardno);
            if(reader != null && StringUtils.isNotBlank(reader.getRdRoleId())){
                ReaderRoler roler = readerRolerService.get(reader.getRdRoleId());
                reader.setRoler(roler);
                session.setAttribute("reader", reader);
                return "redirect:/" + toPage;
            }
            else{
                addMessage(model, "对不起，没有查询到用户信息!");
            }
        }
        return "modules/welcome";
    }
}
